import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *


class PropertyWidget(QWidget):
    def __init__(self, properties=None):
        super().__init__()

        # 创建数据模型
        self.model = QStandardItemModel(0, 2, self)

        # 设置表头
        self.model.setHeaderData(0, Qt.Horizontal, "Key")
        self.model.setHeaderData(1, Qt.Horizontal, "Value")

        # 将属性添加到模型中
        if properties is not None:
            for section, props in properties.items():
                parent_item = self.model.invisibleRootItem()

                # 如果有节标题，则创建一个新的父项
                if section:
                    parent_item = QStandardItem(section)
                    parent_item.setEditable(False)
                    self.model.appendRow(parent_item)

                # 将属性添加到父项中
                for key, value in props.items():
                    key_item = QStandardItem(str(key))
                    value_item = QStandardItem(str(value))
                    parent_item.appendRow([key_item, value_item])

        # 创建树视图
        self.view = QTreeView(self)
        self.view.setModel(self.model)
        self.view.setUniformRowHeights(True)
        self.view.header().setDefaultSectionSize(200)
        self.view.header().setStretchLastSection(False)
        self.view.header().setSectionResizeMode(QHeaderView.ResizeToContents)

        # 布局
        layout = QVBoxLayout()
        layout.addWidget(self.view)
        self.setLayout(layout)


if __name__ == '__main__':
    # 示例属性
    properties = {
        "Section 1": {
            "Key 1.1": "Value 1.1",
            "Key 1.2": "Value 1.2"
        },
        "Section 2": {
            "Key 2.1": "Value 2.1",
            "Key 2.2": "Value 2.2"
        }
    }

    app = QApplication(sys.argv)
    widget = PropertyWidget(properties)
    widget.show()
    sys.exit(app.exec_())
